package com.file;
import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * 导出excel类
 *
 * @author xiongzhengxian
 * @since 2020-03-24
 */
public class ExportExcelUtil {
    /**
     * excel文件名后缀
     */
    private static String file_suffix = ".xlsx";

    /**
     * 导出excel公共方法（easy excel）
     *
     * @param dataList  数据列表
     * @param sheetName 工作簿设置
     * @param fileName  文件名称
     * @param clazz     导出类
     * @param response
     * @throws IOException
     */
    public static void exportExcel(List dataList, String sheetName, String fileName,
                                   Class<? extends BaseRowModel> clazz, HttpServletResponse response) throws IOException {
        fileName += file_suffix;
        fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
        //字节输出流
        OutputStream out = getOutputStream(fileName, response);
        ExcelWriter writer = EasyExcelFactory.getWriter(out);
        writer.write(dataList, getSheet(sheetName, clazz));
        writer.finish();
        out.flush();
        out.close();
    }

    /**
     * 获取输入出流
     *
     * @param fileName 下载文件名称
     * @param response
     * @return
     * @throws IOException
     */
    private static ServletOutputStream getOutputStream(String fileName, HttpServletResponse response) throws IOException {
        ServletOutputStream out = null;
        response.setContentType("application/octemt-stream; charset=iso-8859-1");
        StringBuffer contentDisposition = new StringBuffer("attachment; filename=\"");
        contentDisposition.append(fileName).append("\"");
        response.setHeader("Content-disposition", contentDisposition.toString());
        return response.getOutputStream();
    }

    /**
     * 设置工作簿
     *
     * @param sheetName
     * @param clazz
     * @return
     */
    private static Sheet getSheet(String sheetName, Class<? extends BaseRowModel> clazz) {
        Sheet sheet = new Sheet(1, 0, clazz);
        if (sheetName.isEmpty() || null == sheetName) {
            sheetName = "sheet";
        }
        sheet.setSheetName(sheetName);
        return sheet;
    }
}

